
define([
    "jquery",
    "IO",
    "UPLOADUI",
    "UPLOAD",
    "jqueryUI",
    "bootbox",
    "test",
], function ($, IO, upui, up, jui, bootbox, definebt) {
    var selectTime;//当前选中的时间
    var live_id; //直播标识
    var doctor_id;//直播医生
    var nowdatetimes=[];//当日直播所有时段数组
    $(function(){
        var myDate = new Date();
        //获得年分
        var year= myDate.getFullYear();
        //获得月份
        var month= myDate.getMonth()+2;
        //获得当前月份的天数
        var day=new Date(year,month,0).getDate();
        var timeShow=year+"-"+month+"-"+day;
        var selecTimeShow= $("#ff").attr('selectTime');
        if(selecTimeShow==="undefined"){
            $('#datetimepicker').datetimepicker({
                minView: "month", //选择日期后，不会再跳转去选择时分秒
                format: "yyyy-mm-dd", //选择日期后，文本框显示的日期格式
                language: 'zh-CN', //汉化
                autoclose:true, //选择日期后自动关闭
                endDate :timeShow,
            });
            var current_date= getNowFormatDate();//获得当前时间
            selectTime=current_date;
            var doctor_id="";
            gettable(doctor_id,selectTime);
        }else{
            $('#datetimepicker').datetimepicker({
                minView: "month", //选择日期后，不会再跳转去选择时分秒
                format: "yyyy-mm-dd", //选择日期后，文本框显示的日期格式
                language: 'zh-CN', //汉化
                autoclose:true, //选择日期后自动关闭
                endDate :timeShow,
                initialDate:selecTimeShow
            });
            selectTime=selecTimeShow;
            var doctor_id="";
            gettable(doctor_id,selecTimeShow);
        }

    });
    //获取当前日期
    function getNowFormatDate() {
        var date = new Date();
        var seperator1 = "-";
        var seperator2 = ":";
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        var currentdate = year + seperator1 + month + seperator1 + strDate;
        return currentdate;
    }
    //获取当前时间(yyyy-MM-dd hh:mm:ss)
    function getNowFormatDate2() {
        var date = new Date();
        var seperator1 = "-";
        var seperator2 = ":";
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
            + " " + date.getHours() + seperator2 + date.getMinutes()
            + seperator2 + date.getSeconds();
        return currentdate;
    }
    //日期时间格式(yyyy/MM/dd)
    function getNowFormatDate3(selectTime){
        var year=selectTime.substr(0,4);
        var month=selectTime.substr(5,2);
        var days=selectTime.substr(8,2);
        if(month.substr(0,1)==0){
            month=month.substr(1,1);
        }
        if(days.substr(0,1)==0){
            days=days.substr(1,1);
        }

        return year+"/"+month+"/"+days;

    }

    //表格列表
    function gettable(doctor_id,selectTime){

        var grid;
        //每列数据列性
        var columns = [
            {
                title: '直播日期',
                dataIndex: 'end_time',
                dataSource: function (data, datarow, gridobj, current_column) {
                    var date= data[datarow].end_time;
                    return "<span>" + date.substr(0, 10) + "</span>";
                }
            },
            {
                title: '直播时间',
                dataIndex: 'plan_time',
                dataSource: function (data, datarow, gridobj, current_column) {
                    var myDate=new Date(data[datarow].plan_time)
                    myDate.setHours(myDate.getHours() + 1);
                    return "<span>" + data[datarow].plan_time +"</span>";
                }
            },
            {
                title: '直播医生',
                dataIndex: 'realname',
                dataSource: function (data, datarow, gridobj, current_column) {

                    return "<a href='#'  data-toggle='modal' data-target='#myModal' class='detail2' doctor_id="+data[datarow].doctor.doctor_id+"><span style='color: #6ab7ad;'>" + data[datarow]['doctor'].realname+ "</span></a>";
                }
            },
            {
                title: '直播主题',
                dataIndex: 'live_title',
                dataSource: function (data, datarow, gridobj, current_column) {
                    return "<span>" + data[datarow].live_title + "</span>";
                }
            },
            {
                title: '直播状态',
                dataIndex: 'status',
                dataSource: function (data, datarow, gridobj, current_column) {
                    if(data[datarow].status ==0){
                        return "<span>" + '未开始'+ "</span>";
                    }
                    else if(data[datarow].status ==1){
                        return "<span>" + '进行中'+ "</span>";
                    }
                    else{
                        return "<span>" + '已结束'+ "</span>";
                    }
                }
            }
            ,
            {
                title: '操作',
                dataIndex: 'action',
                dataSource: function (data, datarow, gridobj, current_column) {
                    return "<a href='#'  data-toggle='modal' data-target='#myModaledit' live_id="+data[datarow].live_id+" class='detail' realname="+data[datarow]['doctor'].realname+" datetime="+data[datarow].end_time+" live_title="+data[datarow].live_title+" plan_time="+data[datarow].plan_time+" doctor_id="+data[datarow].doctor.doctor_id+"><span style='color: #6ab7ad;'>" + "查看详情" + "</span></a>";
                }
            }
        ];
        //数组初始化

        function dataInit(current_date) {

            grid = new Grid("/api/lives_b/list", $("#table_my_toast"), $("#paging_my_toast"), 1, 10, columns, get_input_param(doctor_id,selectTime), 10);

            //初始化
            grid.Init();
        }

        //获取输入框内容
        function get_input_param(doctor_id,selectTime) {

            var param="doctor_id="+doctor_id+"&current_date="+selectTime;
            return param;
        }
        dataInit(doctor_id,selectTime);
    }

    //点击查看详情
    $(document).on("click",".detail",function(){
        live_id=$(this).attr("live_id");//获得获得直播标识
        var liveTitle=$(this).attr('live_title');///直播标题
        var realname=$(this).attr('realname');//直播医生
        var datetime= $(this).attr("datetime")//获得直播日期
        var plan_time=$(this).attr("plan_time")//获得直播时间
        doctor_id=$(this).attr("doctor_id")//获得直播医生id
        var pamars={};
        pamars.live_id=live_id;
        IO.post("/api/lives",pamars,function(d){
            if(d.code=="0"){
                //绑定数据
                $('#txtLiveDoctor').val(realname);//直播医生
                $('#txtLiveTitle').val(liveTitle);
                $('#txtLiveDate').attr('placeholder',datetime.substr(0,10)+"  //此项目默认填写不可更改");//直播日期
                var time=plan_time
                if(time=="08:30~09:30"){
                    $('#txtLiveTime').val(0);
                }else if(time=="10:00~11:00"){
                    $('#txtLiveTime').val(1);
                }else if(time=="14:00~15:00"){
                    $('#txtLiveTime').val(2);
                }else if(time=="15:30~16:30"){
                    $('#txtLiveTime').val(3);
                }else{
                    $('#txtLiveTime').val(-1);
                }
                $('#txtLiveNote').val(d.data.live_desc);//直播内容
                $('#txtLiveHot').val(d.data.people_count);//直播热度
                $('#txtLiveStartTime').val(d.data.start_time);//直播开始时间
                $('#txtLiveEndTime').val(d.data.end_time);//直播结束时间

                //时间判定,修改,删除按钮是否显示
                // 获得当前时间
                var nowTime=Date.parse( getNowFormatDate().replace(/-/g,"/"));
                var selectTime2=Date.parse(selectTime.replace(/-/g,"/"));
                var a=(selectTime2-nowTime)/3600/1000;//时间戳(小时)
                if(a<0){
                    $('#btn_update').hide();
                    $('#btn_delete').hide();
                }else if(a==0){
                    //日期相等时,判断时间段
                    var datetime1= selectTime.substr(0,10)+" 08:30:00";
                    var datetime2= selectTime.substr(0,10)+" 10:00:00";
                    var datetime3= selectTime.substr(0,10)+" 14:00:00";
                    var datetime4= selectTime.substr(0,10)+" 15:30:00";
                    //获得当前时间(yyyy-MM-dd)
                    var nowdatetime =getNowFormatDate2();
                    var nowdatetime=Date.parse(nowdatetime.replace(/-/g,"/"));
                    var datetime1=Date.parse(datetime1.replace(/-/g,"/"));
                    var datetime2=Date.parse(datetime2.replace(/-/g,"/"));
                    var datetime3=Date.parse(datetime3.replace(/-/g,"/"));
                    var datetime4=Date.parse(datetime4.replace(/-/g,"/"));
                    if(nowdatetime<datetime1){
                        $('#btn_update').hide();
                        $('#btn_delete').show();
                    }else if(nowdatetime>=datetime1&&nowdatetime<=datetime2){
                        if(time=="08:30:00"){
                            $('#btn_update').hide();
                            $('#btn_delete').hide();
                        }else{
                            $('#btn_update').hide();
                            $('#btn_delete').show();
                        }
                    }else if(nowdatetime>=datetime2&&nowdatetime<=datetime3){
                        if(time=="08:30:00"||time=="10:00:00"){
                            $('#btn_update').hide();
                            $('#btn_delete').hide();
                        }else{
                            $('#btn_update').hide();
                            $('#btn_delete').show();
                        }
                    }else if(nowdatetime>=datetime2&&nowdatetime<=datetime4){
                        if(time=="08:30:00"||time=="10:00:00"||time=="14:00:00"){
                            $('#btn_update').hide();
                            $('#btn_delete').hide();
                        }else{
                            $('#btn_update').hide();
                            $('#btn_delete').show();
                        }
                    }else if(nowdatetime>datetime4){
                        $('#btn_update').hide();
                        $('#btn_delete').hide();
                    }
                }else if(a>0){
                    var nowMonth=getNowFormatDate().substr(5,2);//获得当前月份
                    var nextMonth=selectTime.substr(5,2);//获得选择月份
                    if(parseInt(nowMonth)==parseInt(nextMonth)){ //当月内
                        $('#btn_update').hide();
                        $('#btn_delete').show();
                    }else if(parseInt(nowMonth)+1==parseInt(nextMonth)){//下个月
                        $('#btn_update').show();
                        $('#btn_delete').show();
                    }else if(parseInt(nowMonth)+2==parseInt(nextMonth)){//下下个月
                        $('#btn_update').hide();
                        $('#btn_delete').hide();
                    }
                }
            }
        })

        //先查数据绑定到页面上,然后手动调用modal
        $('#myModaledit').modal();
    });

    //点击医生姓名获得医生详情
    $(document).on("click",".detail2",function(){
        var doctor_id=$(this).attr("doctor_id");
        if(doctor_id){
            //获得申请详情
            var pamars={};
            pamars.doctor_id=doctor_id;
            IO.post("/api/doctorDetails",pamars,function(d){

                if(d.code=="0"){
                    $("#realname2").val(d.data.realname);//真实姓名
                    doctor_type_id_Show(d.data.doctorType.doctor_type_id);//医生等级
                    $("#service_count").val(d.data.service_count);//服务单数
                    $("#fans_count").val(d.data.fans_count);//粉丝数
                    $("#idcard").val(d.data.idcard);//身份证号
                    $("#card_num").val(d.data.card_num);//银行卡号
                    $("#accountBalance").val(d.data.asset);//当前余额
                    province_city_area_nameShow(d.data.province_id,d.data.city_id,d.data.area_id);//省,市,区
                    hospital_department_jobTitle_nameShow(d.data.hospital.hospital_id,d.data.department.department_id,d.data.duty.duty_id);//医院全称,科室,职称
                    $("#departmentTel").val(d.data.depart_phone);//科室电话
                    $(".addimage1").attr( "src",d.data.pic_neg); //手持证件照
                    $(".addimage2").attr( "src",d.data.pic_pos );//正面免冠照
                    $("#goodCase").val(d.data.specialty);//擅长病症
                    $("#txtShow").val(d.data.introduction);//个人简介
                }
            })
            //先查数据绑定到页面上,然后手动调用modal
            $('#myModal').modal();
        }
    });

    //点击删除按钮
    $("#btn_delete").off("click");
    $("#btn_delete").on("click",function() {
        var pamars = {};
        pamars.live_id = live_id;
        IO.post("/api/livesDelete", pamars, function (d) {
            if (d.code == "0") {
                $('#myModaledit').modal("hide");
                bootbox.alert({
                    buttons: {
                        ok: {
                            label: '确定',
                            className: 'btn-myStyle'
                        }
                    },
                    message: '删除直播成功',
                    callback: function() {
                        location.href = '/96053/directseeding?selectTime='+selectTime;
                    },
                    title: "提示",
                });

            } else {
                $('#myModaledit').modal("hide");
                bootbox.alert({
                    buttons: {
                        ok: {
                            label: '确定',
                            className: 'btn-myStyle'
                        }
                    },
                    message: '删除直播失败',
                    callback: function() {
                        //location.href = '/96053/directseeding';
                    },
                    title: "提示",
                });

            }

        })
    })
    //点击修改按钮
    var isclick=0;//记录点击
    //点击修改按钮
    $("#btn_update").off("click");
    $("#btn_update").on("click",function(){
        if(isclick==0){//进入修改状态
            isclick=1;
            $('#btn_update').text("保存直播");
            $('#txtLiveTime').attr("disabled",false);
            $('#txtLiveTime').removeAttr("readOnly");
            $('#txtLiveNote').removeAttr("readOnly");
            $('.ylm').css("background","gray");

        }else{//开始保存修改数据

            if($("#txtLiveTime").val()==-1){
                alert('请选择直播时间');
                return;
            }
            var live_title=$("#txtLiveNote").val();
            if(live_title==""){
                alert('请输入直播内容');
                return;
            }
            if(live_title.length>20){
                alert('输入直播内容字数超过20');
                return;
            }
            var pamars={};
            pamars.live_id=live_id;//直播标识
            var datetime=getNowFormatDate3(selectTime);//直播日期
            pamars.date=datetime;
            pamars.live_title=$("#txtLiveTitle").val();//直播标题
            pamars.live_desc=$("#txtLiveNote").val();//直播内容
            var time=$("#txtLiveTime").find("option:selected").text();//直播时间
            pamars.time=time;
            var isbreak;
            for(var i=0;i<nowdatetimes.length;i++){
                if(nowdatetimes[i].time==time&&nowdatetimes[i].doctor_id==doctor_id){
                    isbreak=1;
                    break;
                }
            }
            if(isbreak==1){
                bootbox.alert({
                    buttons: {
                        ok: {
                            label: '确定',
                            className: 'btn-myStyle'
                        }
                    },
                    message: '当日该直播时段已经被选择',
                    callback: function() {
                    },
                    title: "提示",
                });
                return;
            }
            IO.post("/api/livesUpdate",pamars,function(d){
                if(d.code=="0"){
                    $('#btn_update').text("修改直播");
                    $('#txtLiveTime').attr("disabled",true);
                    $('#txtLiveTime').attr("readOnly",'readonly');
                    $('#txtLiveNote').attr("readOnly",'readonly');
                    $('.ylm').css('background', null);
                    isclick=0;
                    $('#myModaledit').modal("hide");
                    bootbox.alert({
                        buttons: {
                            ok: {
                                label: '确定',
                                className: 'btn-myStyle'
                            }
                        },
                        message: '修改直播成功',
                        callback: function() {
                            location.href = '/96053/directseeding?selectTime='+selectTime;
                        },
                        title: "提示",
                    });

                }else{
                    $('#myModaledit').modal("hide");
                    bootbox.alert({
                        buttons: {
                            ok: {
                                label: '确定',
                                className: 'btn-myStyle'
                            }
                        },
                        message: '修改直播失败',
                        callback: function() {
                            //location.href = '/96053/directseeding';
                        },
                        title: "提示",
                    });

                }
            });

        }

    })

    //点击日历控件
    $('#datetimepicker')
        .datetimepicker()
        .on('changeDate', function(ev){
            nowdatetimes.length=0;
            var test = (ev.date).toString();
            var d=new Date(test);
            var a = [d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate(), d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds()];
            for(var i = 0, len = a.length; i < len; i ++) {
                if(a[i] < 10) {
                    a[i] = '0' + a[i];
                }
            }
            str = a[0] + '-' + a[1] + '-' + a[2];
            selectTime=str;
            var doctor_id="";
            gettable(doctor_id,selectTime);
            // 获得当日已经选择的直播时段
            var pamars2={};
            pamars2.doctor_id=doctor_id;
            pamars2.current_date=selectTime;
            var key;//直播id
            var value;//时间段
            var doctor;//医生
            IO.post("/api/lives_b/list",pamars2,function(d){
                if(d.code=="0"){
                    for(var i=0;i<d.data.length;i++){
                        key = d.data[i].live_id;
                        value =d.data[i].plan_time;
                        doctor= d.data[i].doctor.doctor_id;
                        nowdatetimes.push({
                            'live_id': key,
                            'time': value,
                            'doctor_id':doctor,
                        });
                    }
                }

            });
        });

    //点击搜索按钮
    $("#btnsearch").click(function(){
         if($("#selectDoctor").val()==-1){
             gettable("",selectTime);
         }else{
             gettable($("#selectDoctor").val(),selectTime);
         }

    });


    //根据省id,城市id,区id,初始数据到省,市,区,三个下拉框
    function province_city_area_nameShow(province_id,city_id,area_id){
        var provinceList = JSON.parse($("#provinceA").val());

        for ( var obj in provinceList) {
            if (provinceList[obj].code == province_id) {
                $("#province_id").val(provinceList[obj].code);//下拉框绑定省
                //获得省所有市,并读出当前用户所在市
                $("#city_id").empty();
                $("#city_id").append("<option value='-1' selected>请选择</option>");
                for (var obj1 in provinceList){
                    if(provinceList[obj1].name == $("#province_id").find("option:selected").text()){
                        for (var x in provinceList[obj1].cityList){
                            var city = provinceList[obj1].cityList;
                            $("#city_id").append("<option value='"+city[x].code+"'>"+city[x].name+"</option>");
                        }
                        $("#city_id").val(city_id);//下拉框绑定市
                        $("#area_id").empty();
                        $("#area_id").append("<option value='-1' selected>请选择</option>");
                        for (var obj2 in provinceList){
                            if(provinceList[obj2].name == $("#province_id").find("option:selected").text()){
                                var city2 = provinceList[obj2].cityList;
                                for (var x2 in city2){
                                    if ($("#city_id").find("option:selected").text()==city[x2].name){
                                        var area = city[x2].areaList;
                                        for (var y in area){
                                            $("#area_id").append("<option value='"+area[y].code+"'>"+area[y].name+"</option>");
                                        }
                                        $("#area_id").val(area_id);//下拉框绑定市
                                    }

                                }
                            }
                        }

                    }
                }

            }
        }
    }
    //根据医院id初始化医院下拉框数据
    function hospital_department_jobTitle_nameShow(hospital_id,department_id,jobTitle_id){
        //获得所有医院
        var pamars={};
        IO.post("/api/hospitalsAll",pamars,function(d){
            if(d.code=="0"){
                $("#hospital_id").empty();
                $("#hospital_id").append("<option value='-1' selected>医院全称</option>");
                for (var i=0;i< d.data.length;i++){
                    $("#hospital_id").append("<option value='"+d.data[i].hospital_id+"'>"+d.data[i].hospital_name+"</option>");
                }
                $("#hospital_id").val(hospital_id);//下拉框绑定医院全称

                var pamar={};
                pamar.hospital_id= $("#hospital_id option:selected").val();
                $("#department_id").empty();
                $("#jobTitle_id").empty();
                $("#department_id").append("<option value='-1' selected>请选择</option>");
                $("#jobTitle_id").append("<option value='-1' selected>请选择</option>");

                IO.post("/api/hospitalsAllDepartments",pamar,function(d){
                    if(d.code=="0"){
                        for(var i=0;i< d.data.length;i++){
                            $("#department_id").append("<option value='"+d.data[i].department_id+"'>"+d.data[i].department_name+"</option>");
                        }
                        $("#department_id").val(department_id);//下拉框绑定科室
                    }
                });
                IO.post("/api/hospitalsAllDuty",pamar,function(d){
                    if(d.code=="0"){
                        for(var i=0;i< d.data.length;i++){
                            $("#jobTitle_id").append("<option value='"+d.data[i].duty_id+"'>"+d.data[i].duty_name+"</option>");
                        }
                        $("#jobTitle_id").val(jobTitle_id);//下拉框绑定职称
                    }
                });
            }
        })
    }

    //手持证件照片上传
    $('#fileupload1').fileupload({
        url: '/upload',
        dataType: 'json',
        autoUpload: true,
        acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
        maxFileSize: 10000000, // 10 MB
        disableImageResize: /Android(?!.*Chrome)|Opera/
            .test(window.navigator.userAgent),
        previewMaxWidth: 150,
        previewMaxHeight: 150,
        previewCrop: true
    }).on('fileuploadadd', function (e, data) {
        document.getElementById('upimgs1').src = '/images/loading.gif';
    }).on('fileuploadprocessalways', function (e, data) {

    }).on('fileuploadprogressall', function (e, data) {

    }).on('fileuploaddone', function (e, data) {
        var alt = $(e.target).attr('alt');
        if (!alt)
            alt = '';

        $("#upimgs1" + alt).attr("src", data._response.result.url);
    });

    //正面证件照片上传
    $('#fileupload2').fileupload({
        url: '/upload',
        dataType: 'json',
        autoUpload: true,
        acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
        maxFileSize: 10000000, // 10 MB
        disableImageResize: /Android(?!.*Chrome)|Opera/
            .test(window.navigator.userAgent),
        previewMaxWidth: 150,
        previewMaxHeight: 150,
        previewCrop: true
    }).on('fileuploadadd', function (e, data) {
        document.getElementById('upimgs2').src = '/images/loading.gif';
    }).on('fileuploadprocessalways', function (e, data) {

    }).on('fileuploadprogressall', function (e, data) {

    }).on('fileuploaddone', function (e, data) {
        var alt = $(e.target).attr('alt');
        if (!alt)
            alt = '';

        $("#upimgs2" + alt).attr("src", data._response.result.url);
    });
    //根据医生类别id 绑定下拉框
    function doctor_type_id_Show(doctor_type_id){
        //获得医院所有医生类型
        var pamars2={};
        IO.post("/api/doctorTypeAll",pamars2,function(d){
            if(d.code=="0"){
                $("#doctor_type_id").empty();
                $("#doctor_type_id").append("<option value='-1' selected>请选择</option>");
                for (var i=0;i< d.data.length;i++){
                    $("#doctor_type_id").append("<option value='"+d.data[i].doctor_type_id+"'>"+d.data[i].doctor_type_name+"</option>");
                }
                $("#doctor_type_id").val(doctor_type_id);//下拉框绑定医院全称

            }
        });

    }

    //选取医院科室名称改变联动职称名称联动
    $("#hospital_id").on("change",function(){
        $("#department_id").empty();
        $("#jobTitle_id").empty();
        //获得所属医院的科室名称
        var pamars={};
        pamars.hospital_id= $("#hospital_id option:selected").val();
        $("#department_id").append("<option value='-1' selected>请选择</option>");
        $("#jobTitle_id").append("<option value='-1' selected>请选择</option>");
        IO.post("/api/hospitalsAllDepartments",pamars,function(d){
            if(d.code=="0"){
                for(var i=0;i< d.data.length;i++){
                    $("#department_id").append("<option value='"+d.data[i].department_id+"'>"+d.data[i].department_name+"</option>");
                }
            }
        });
        IO.post("/api/hospitalsAllDuty",pamars,function(d){
            if(d.code=="0"){
                for(var i=0;i< d.data.length;i++){
                    $("#jobTitle_id").append("<option value='"+d.data[i].duty_id+"'>"+d.data[i].duty_name+"</option>");
                }
            }
        });
    });

});